package com.java.agent.util;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Constructor;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class LoadClass {

    public static ClassLoader DEFAULT_CLASSLOAD;

    /**
     * 获取某个包下的所有类
     * */
    public static void getClasses(String packageName) throws Exception {
        Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".", "/"));
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            if (url != null) {
                String protocol = url.getProtocol();
                String packagePath = url.getPath().replaceAll("%20", " ");
                if (protocol.equals("file")) {
                    addClass(packagePath, packageName);
                } else if (protocol.equals("jar")) {
                    JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                    if (jarURLConnection != null) {
                        JarFile jarFile = jarURLConnection.getJarFile();
                        if (jarFile != null) {
                            Enumeration<JarEntry> jarEntries = jarFile.entries();
                            while (jarEntries.hasMoreElements()) {
                                JarEntry jarEntry = jarEntries.nextElement();
                                String jarEntryName = jarEntry.getName();
                                if (jarEntryName.startsWith(packageName.replace(".","/")) && jarEntryName.endsWith(".class")) {
                                    String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                    doAddClass( className);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private static void addClass( String packagePath, String packageName) throws Exception {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
            }
        });
        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile()) {
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if (StringUtils.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                }
                doAddClass( className);
            } else {
                String subPackagePath = fileName;
                if (StringUtils.isNotEmpty(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                String subPackageName = fileName;
                if (StringUtils.isNotEmpty(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                addClass( subPackagePath, subPackageName);
            }
        }
    }

    /**
     * 加载类（默认将初始化类）
     */
    private static void doAddClass( String className) throws Exception {
        Constructor<?> declaredConstructor = Class.forName(className).getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        declaredConstructor.newInstance();
    }
}
